package com.duomizhibo.phonelive.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.duomizhibo.phonelive.alipay2.AuthResult;
import com.duomizhibo.phonelive.alipay2.OrderInfoUtil2_0;
import com.duomizhibo.phonelive.alipay2.PayResult;
import com.duomizhibo.phonelive.base.BaseApplication;
import com.google.gson.Gson;
import com.duomizhibo.phonelive.AppConfig;
import com.duomizhibo.phonelive.AppContext;
import com.duomizhibo.phonelive.R;
import com.duomizhibo.phonelive.adapter.RechangeAdapter;
import com.duomizhibo.phonelive.alipay.Keys;
import com.duomizhibo.phonelive.bean.RechargeJson;
import com.duomizhibo.phonelive.ui.customviews.ActivityTitle;
import com.duomizhibo.phonelive.utils.DialogHelp;
import com.duomizhibo.phonelive.utils.StringUtils;
import com.duomizhibo.phonelive.WxPay.WChatPay;
import com.duomizhibo.phonelive.alipay.AliPay;
import com.duomizhibo.phonelive.api.remote.ApiUtils;
import com.duomizhibo.phonelive.api.remote.PhoneLiveApi;
import com.duomizhibo.phonelive.base.ToolBarBaseActivity;
import com.duomizhibo.phonelive.bean.RechargeBean;
import com.duomizhibo.phonelive.widget.BlackButton;
import com.duomizhibo.phonelive.widget.BlackEditText;
import com.duomizhibo.phonelive.widget.BlackTextView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.InjectView;
import okhttp3.Call;

/**
 * 我的钻石
 */
public class UserDiamondsActivity extends ToolBarBaseActivity {

    @InjectView(R.id.lv_select_num_list)
    ListView mSelectNumListItem;

    @InjectView(R.id.view_title)
    ActivityTitle mActivityTitle;

    private List<RechargeBean> mRechargeList = new ArrayList<>();

    private final int WX_PAY = 1;
    private final int ALI_PAY = 2;

    private int PAY_MODE = WX_PAY;

    private BlackTextView mCoin;
    private View mHeadView;

    private WChatPay mWChatPay;
    private AliPay mAliPayUtils;

    private RechangeAdapter mRechangeAdapter;
    private RechargeJson mRechargeJson;


    public static  String RSA_PRIVATE = "";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

//    public static final String RSA_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDklPqDHUU0efceV10d6FTlPa7OuBBdN6GD9MAYoNSfD6f3lb2rdLL7FTM6zR+99fMtGJ2CbhuhQqDxHyVEdTBcI4s+wFGwELnsQSf/pjlgKr1BtF2f5utbELpBnZ1Q+AgYR3OpMye08aDA9qjANKWFaOu79lBEnonHZMFmxgQV1Kekvp2HhakkhwHX+g5nqwHaR/P4a9xrxa6Xw/iES3kFBH2cxqo7O5zt9d4ZXHHMkfhDE/DFk954o+CnmaGQaXVoFkuWtAAJ+o//ncwQ+gmOoXHPd4ojB6Oy23xT7ffjUhWAibuIdnWY9sG0xllo2lEqBIflLU/bzl8of1u5ywMfAgMBAAECggEAGXRFmUgvJrLWQ/iyk9wFaCnAR6DToa3KPKmKorN2OehCah2wq2EpdTBdLhUdjcfPtpvhHl8okIKc7XzsZ30tT3Vd0jUUY6jZK2fuDlfyV7UqsiBltKLAXrm0JA5rMFMOg7WhOZxKtamanyJYlF7Id9zBM4MwWRPWf+/GYa13Uv7PZzL8iE9xbllTqw8rKMViCsZztDx2FcckZIt8ZQD989l5Du6+3U5M35lWPMQ41wRBcrnms+kql4oBoGusUA0EjwDkGlikB+STwTPCDjtSUyl9QmILGT0V0zytOLSQING2jxaRdMivX0KOWihMuTF6qHQxgJ0a/q1PGpgeHsSCEQKBgQD8mBIvSbh0YuMntE8rmtYAxz39PUcxewCmq3g/jQp4iHO5B+0dkrZMfDqgqx8H5wTig4BbrZTH3SoU/KLppC/1kPcV0XvWBnHO3lI3VwLO4SWDQkZzVT0FhktHqWiBVaJOl8TXdVyQkPSoEKg3h5+1OZGJL/IP8A8Sf6xYqQKrpQKBgQDnqgUwCZsxm07kcFGju1gY/fmHyjiUsU4uK0zh2Yd5r96t+heTHGDBrg7xKs29IO9bhPLf4wh4uypWffKxnk32ryb1ZMx2C17QOKyiDnSmI9gaMXOvfSzwhrJJGm2UrBHgju37vW960RQS4Y06l7K4xpsyLJ2xTQsTalem/VPIcwKBgQDll5AH3XlEiNGyOCkyGEXmZTOKKBW6+vOnivn8wcU/s7+D8plrJPyAXvanLYNCGpENFrwoGInAdN2YP94QgkV5bq+37DYkXq05fEi8tmD+DBWdzjLdCCA0ElIArBIqZNznlPm9YZambKuEy8cq2iKnhdEsIiFirS/1/4h2+gBMZQKBgCPzFF8B/p1SFooIjAK2fdNTBjf2P5WDdjhf68xYb1eI3StuVd40Vyd3FUaDd+3TgJFZLj9kAdqKYOWPIexCPqL7RzZpb/kZhpsVUGTNjXiCs3RNHECtUh35KQ2DFmIt2ZBZXcDlArmyXEUZz0q6Y7ecylSc69OpuwBGTlfRlADVAoGBAKM3d+iZ3464t1cGuVUc5nB5ISKr6+UtOkEXHNurFpCDMQQHafyCCkptSqz/BSBb4w/vbthKOf22R5aikBFBsLGQVPHN+YgCnYZmOUZc19FyvaqOAcOlCUKeKbu6fZFagAcR+avSYHMS3DtesWa8Qbp2gT/hyNhAUk7lqhVJqpRF";

    /**
     * 支付宝支付业务：入参app_id
     */

//    2016011301090584
    public   String APPID = "2016011301090584";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    Log.d(msg.obj.toString(), "444444444444");

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(UserDiamondsActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                    } else {

                        Toast.makeText(UserDiamondsActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(UserDiamondsActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(UserDiamondsActivity.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_diamonds;
    }

    @Override
    public void initView() {

        mActivityTitle.setTitle("我的" + AppConfig.CURRENCY_NAME);
        mHeadView = getLayoutInflater().inflate(R.layout.view_diamonds_head, null);
        mCoin = (BlackTextView) mHeadView.findViewById(R.id.tv_coin);

        mSelectNumListItem.addHeaderView(mHeadView);

        mSelectNumListItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position == 0) return;
                DialogHelp.getSelectDialog(UserDiamondsActivity.this, new String[]{"支付宝", "微信"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        PAY_MODE = i == 0 ? ALI_PAY : WX_PAY;

                        actionPay(String.valueOf(mRechargeList.get(position - 1).money), mRechargeList.get(position - 1).coin
                                , mRechargeList.get(position - 1).id);
                    }
                }).create().show();


            }
        });
        mSelectNumListItem.setDivider(null);
        mRechangeAdapter = new RechangeAdapter(mRechargeList);
        mSelectNumListItem.setAdapter(mRechangeAdapter);

        mActivityTitle.setReturnListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    @Override
    public void initData() {
        requestData();

        mAliPayUtils = new AliPay(this);
        mWChatPay = new WChatPay(this);


    }

    private void actionPay(final String money, final String num, String changeid) {

        if (PAY_MODE == ALI_PAY && checkPayMode()) {


            final String subject = num + AppConfig.CURRENCY_NAME;
            final String body = num + AppConfig.CURRENCY_NAME;
            final String total_fee = money;
            String uid = AppContext.getInstance().getLoginUid();

            PhoneLiveApi.getAliPayOrderNum(uid, changeid, num, money, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Toast.makeText(UserDiamondsActivity.this, "支付失败", Toast.LENGTH_SHORT);
                }

                @Override
                public void onResponse(String response, int id) {

                    Log.d(response.toString(), "3333333333333333333");
                    String mOut_trade_no = null;
                    JSONArray res = ApiUtils.checkIsSuccess(response);

                    if (null!=res){
                        try {
                             mOut_trade_no = res.getJSONObject(0).getString("orderid");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    final String url = AppConfig.AP_LI_PAY_NOTIFY_URL;

//            mAliPayUtils.initPay(money, num,changeid);
//                    Toast.makeText(UserDiamondsActivity.this, "支付宝", Toast.LENGTH_SHORT).show();
                    String name =num+"美币";
//                String body = "20120212" + "," + "0" + "," + 2 + "," + BaseApplication.basePreferences.readUid();
                    String body = mOut_trade_no + "," + "0.01" + "," + 2;

//                String body = "0";
                    boolean rsa2 = true;
//                    Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, mOut_trade_no, "0.01", name,url);
                    Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2, body, mOut_trade_no,money, name,url);
//                Map<String, String> authInfoMap = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
                    String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);


//                String sign = OrderInfoUtil2_0.getSign(authInfoMap, RSA_PRIVATE, rsa2);

                    String sign = null;
                    try {
                        sign = OrderInfoUtil2_0.getSign(authInfoMap, RSA_PRIVATE, rsa2);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    final String authInfo = info + "&" + sign;


//                    "&sign=\"" + sign
                    Log.i("123456789", authInfo);
                    Runnable authRunable = new Runnable() {
                        @Override
                        public void run() {
                            // 构造PayTask对象
                            AuthTask authTask = new AuthTask(UserDiamondsActivity.this);

                            // 调用支付接口,获取支付结果
                            Map<String, String> result = authTask.authV2(authInfo, true);
                            Log.d(result.toString() + "", "333333333333333");
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;

                            Log.d(msg.what + "", "333333333333333");

                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread authThread = new Thread(authRunable);
                    authThread.start();

                /*    if (null != res) {
                        try {
                            String mOut_trade_no = res.getJSONObject(0).getString("orderid");
                            String price = total_fee;
                            String orderInfo = getOrderInfo(mOut_trade_no, subject, body, String.valueOf(price), url);
                            String sign = sign(orderInfo);
                            try {
                                // 仅需对sign 做URL编码
                                if (sign != null) {
                                    sign = URLEncoder.encode(sign, "UTF-8");
                                }

                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }

                            final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                                    + getSignType();


                            Message msg = new Message();
                            msg.what = ALIPAY;
                            msg.obj = payInfo;
                            mHandler.sendMessage(msg);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } else {
                        Toast.makeText(mPayActivity, "支付失败", Toast.LENGTH_SHORT).show();
                    }*/

                }
            });



        } else if (checkPayMode()) {

            mWChatPay.initPay(money, num, changeid);
        }
    }

    //检查支付配置
    private boolean checkPayMode() {

        if (PAY_MODE == ALI_PAY) {
            if (mRechargeJson.aliapp_switch.equals("1")) {
                return true;
            } else {

                showToast3("支付宝未开启", 0);
                return false;
            }
        } else if (PAY_MODE == WX_PAY) {
            if (mRechargeJson.wx_switch.equals("1")) {
                return true;
            } else {

                showToast3("微信未开启", 0);
                return false;
            }
        }

        return false;

    }

    private void requestData() {

        PhoneLiveApi.requestBalance(getUserID(), getUserToken(), new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                Log.d(response.toString(), "333333333333");

                JSONArray array = ApiUtils.checkIsSuccess(response);

                if (array != null) {

                    try {
                        mRechargeJson = new Gson().fromJson(array.getString(0), RechargeJson.class);
                        mRechargeList.clear();
                        mRechargeList.addAll(mRechargeJson.rules);
                        mRechangeAdapter.notifyDataSetChanged();
                        mCoin.setText(mRechargeJson.coin);

                        //微信支付appid
                        AppConfig.GLOBAL_WX_KEY = mRechargeJson.wx_appid;

                        //支付宝
                        Keys.DEFAULT_PARTNER = mRechargeJson.aliapp_partner;
                        Keys.DEFAULT_SELLER = mRechargeJson.aliapp_seller_id;
//                        Keys.PRIVATE = mRechargeJson.aliapp_key_android;

                        RSA_PRIVATE= mRechargeJson.aliapp_key_android;


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        requestData();

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    //充值结果
    public void rechargeResult(boolean isOk, String rechargeMoney) {
        if (isOk) {
            mCoin.setText(String.valueOf(StringUtils.toInt(mCoin.getText().toString()) +
                    StringUtils.toInt(rechargeMoney)));
        }
    }


}
